package com.jmxcfc.blfsc.ninefour.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jmxcfc.blfsc.ninefour.common.Constants;
import com.jmxcfc.blfsc.ninefour.feign.ISmsClientService;
import com.jmxcfc.blfsc.ninefour.util.AesUtils;
import com.jmxcfc.blfsc.ninefour.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 功能描述:
 * 请求外部的公共实现类
 * 1、http 请求语音获取token
 * 2、feign 请求blfs-sms
 * @author: pay
 * @date: 2024年06月16日 22:03
 */
@Slf4j
@Service
public class RequestApiService {


    @Value("${ninefour.tokenUrl}")
    private String tokenUrl;

    private HttpClientUtil httpClientUtil;

    private ISmsClientService smsClientService;




    @Autowired
    public void setHttpClientUtil(HttpClientUtil httpClientUtil) {
        this.httpClientUtil = httpClientUtil;
    }

    @Autowired
    public void setSmsClientService(ISmsClientService smsClientService) {
        this.smsClientService = smsClientService;
    }
    /**
     *
     * 调⽤接⼝http[s]://[gateway-endpoint]/authority/accessToken?cropId={cropId}
     * 请求⽅式为GET 需要包含以下:
     header:
     x-timestamp: 当前时间戳,格式为: yyyyMMddHHmmss
     x-ciphertext: 密⽂,密⽂为Aes算法加密串,aesKey为:
     {x-timestamp}+'#'+{secret}. 加密算法为Aes({secret}, {aseKey})
     * @param appKey:  客户服务key
     * @param appSecret: 密钥
     * @param timestamp: 当前时间戳,格式为: yyyyMMddHHmmss
     * @return
     */
    public String getToken(String requestNo,String appKey,String appSecret,String timestamp) throws Exception {
        log.info("语音请求流水号requestNo:{},获取accessToken---开始",requestNo);
        if (StringUtils.isBlank(timestamp)) {
            LocalDateTime now = LocalDateTime.now();
            timestamp = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("x-timestamp",timestamp);
        headers.put("x-ciphertext", AesUtils.encrypt(appSecret,timestamp+"#"+appSecret));
        Map<String, Object> uriVariables = new HashMap<>();
        //cropId: 由运营提供(企业信息中的appKey)
        uriVariables.put("cropId",appKey);
        log.info("语音请求流水号requestNo:{},获取accessToken,请求地址:{},请求头部参数:{}",requestNo,tokenUrl, JSON.toJSONString(headers));
        ResponseEntity<JSONObject> responseEntity = httpClientUtil.get(tokenUrl, null, headers, JSONObject.class, uriVariables);
        log.info("语音请求流水号requestNo:{},获取accessToken响应结果:{}",requestNo,responseEntity);
        return getResponseToken(requestNo, responseEntity);
    }

    /**
     * 从响应结果中获取toke
     接口返回结果--示例
     {
     "status":200,
     "code":200,
     "message":"success",
     "data":"flkxvn5limzhjc071361397122652192"
     }
     * @param requestNo
     * @param responseEntity
     * @return
     * @throws Exception
     */
    private String getResponseToken(String requestNo,ResponseEntity<JSONObject> responseEntity) throws Exception {
        int statusCodeValue = responseEntity.getStatusCodeValue();
        HttpHeaders headers = responseEntity.getHeaders();
        log.info("请求流水号requestNo:{},响应头(header)信息--->X-Trace-Id:{}",requestNo,headers.get("X-Trace-Id"));
        if ( Objects.equals(statusCodeValue,200)&&Objects.nonNull(responseEntity.getBody())) {
            JSONObject body = responseEntity.getBody();
            String code = body.getString(Constants.RESP_CODE);
            if (StringUtils.equals(code, Constants.STRING_200)) {
                log.info("请求流水号requestNo:{},获取token密文成功,token密文为:{}", requestNo, body.getString(Constants.RESP_DATA));
                return body.getString(Constants.RESP_DATA);
            }else {
                log.error("请求流水号requestNo:{},获取token密文--->返回状态不正确,code:{},message:{}",requestNo,code,body.get(Constants.RESP_MESSAGE));
                throw new Exception("获取token密文返回状态不正确");
            }
        } else {
            log.error("请求流水号requestNo:{},获取token密文--->响应状态不正确,responseEntity:{}",requestNo,responseEntity);
            throw new Exception("获取token密文响应状态不正确");
        }
    }

}